<template>
    <div class="input-number" :style="{width: width+'px !important',margin:'0 auto',minWidth: width+'px !important'}">
        <el-tooltip ref="tooltip" v-model="showPoper" :hideAfter="3" :content="content" :manual="true" placement="top"
            effect="light">
            <div :class="['el-input']"  @mouseenter="closeMouseenter"
                @mouseleave="closeMouseleave">
                <input
                    class="el-input__inner new-number-input"
                    v-bind="$props"
                    ref="input"
                    v-model="inputValue"
                    :aria-label="label"
                    @blur="blurNumber"
                    @input="handleInput"
                    :disabled="disabled"
                    @change="change"
                    @focus="focusHandle($event)"
                    :style="{color: (color +'!important' || '')}"
                    :class="{'is-error':isError}"
                    />
                <!-- 后置元素 -->
                <span class="el-input__suffix" v-if="inputValue&&isClose&&!color" @click="handlerClose">
                    <span class="el-input__suffix-inner">
                        <i class="el-select__caret el-input__icon el-icon-circle-close"></i>
                    </span>
                </span>
            </div>
        </el-tooltip>        
    </div>
</template>
<script>
import { ElInput } from 'element-plus';
export default {
    components: {ElInput},
    name: 'input-number',
    props:{
        max: {//最大值
            type: Number,
            default: 9999999999
        },
        min: {//最小值
            type: Number,
            default: -Infinity
        },
        color: String,
        cannum: Number,//小数输入限制 [注意:只有限制小数的值的时候!!]
        value: {},
        maxLength: Number,//最大长度
        maxWidth:Number,//最大宽度
        doublelen: Number,//保留几位小数 [注意:整数不写!!]
        placeholder: String,
        width: Number,
        height: Number,
        disabled: {
            type: Boolean
        },
        label: String,
        //显示实际值，如果是空的话什么也不显示，也不现实最小值
        showReal: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            inputValue: '',
            isEmit: false,
            showPoper: false,
            content: '',
            delay: 3000,
            focused: false,
            isError: false,
            isClose: false,//是否显示关闭
        }
    },
     computed: {},
    mounted() {
        let val = this.validate(this.value, true);
        this.inputValue = this.formatter(val);
    },
    created() {
        // console.log('created,this.inputValue', this.inputValue, 'this.value', this.value)

    },
    watch: {        
        value(val) {
            // console.log('watch_value1',val)
            this.isError = false
            if (this.isEmit) {
                this.isEmit = false
                return
            }
            val = String(val);
            val = this.validate(val)
            //val = this.formatter(val)
            if (val != this.inputValue) {
                this.inputValue = val
            }
            this.isEmit = false
        }
    },
    methods:{
        handlerClose: function(){
            this.isError = true;
            let val = this.validate('', true);
            this.inputValue = this.formatter(val);
            this.$emit('input', this.inputValue);
            this.$emit('change', this.inputValue);
        },
        closeMouseleave: function(){
            this.isClose = false;
        },
        closeMouseenter:function(){
            this.isClose = true;
        },
        focusHandle:function(event){
            event.currentTarget.select();
            this.isError = false;
            this.showPoper = false;
        },
        validate(value, hideError) {
            let val = value;
            if ((value == undefined || value == null || value === '')) {
                if (this.showReal) {
                    return val;
                }else {
                    val = this.min;
                }
            }
            if(!this.doublelen&&this.doublelen!=0){
                if(/[^\.]/g.test(value)&&value!='null'&&value!='undefined'){
                    val=parseInt(value);
                }
            }

            if(isNaN(val)){
                val = String(val).replace(/[^\d]/g, "");
            }
            if (this.maxWidth) {
                if(isNaN(val)){
                    val = val.replace(/[^\d]/g, "");
                }
                if (String(val).length > this.maxWidth) {
                    val = String(val).substr(0, this.maxWidth)
                    this.inputValue = val;
                    this.showPoper = !hideError;
                    this.content = '最大长度为' + this.maxWidth;
                }
            } else {
                if (this.doublelen && String(val).indexOf('.') > 0)
                {
                    val = String(val).replace('..', '.')
                    let vals = String(val).split('.');
                    if (vals[1].length > this.doublelen) {
                        val = vals[0] + '.' + vals[1].substr(0, this.doublelen)
                        this.showPoper = !hideError;
                        this.content = '小数点后最大位数为：' + this.doublelen
                    }
                }

                if (val < this.min) {
                    val = this.min;
                    this.showPoper = !hideError;
                    this.content = '输入的数字不能小于最小值：' + this.min
                }
                if (this.max && this.max < val) {
                    //有无小数点的最大值显示
                    if (String(val).indexOf('.') == -1) {
                        if(String(this.max).indexOf('.') == -1){//最大值不是小数
                            let len = String(this.max).length;
                            val = String(val).substr(0, len);
                            if (val > this.max) {
                                len = String(this.max).length - 1;
                                val = String(val).substr(0, len);
                            }
                        }else{
                            let prevMax = String(this.max).split('.')[0];//小数点前面的值 
                            let lastMax = String(this.max).split('.')[1];                           
                            let len = String(prevMax).length;
                            if(val> prevMax){
                                val = String(prevMax).substr(0, len) +'.'+ lastMax;
                            }
                        }
                       
                    } else {
                        if(String(this.max).indexOf('.') == -1){//最大值不是小数
                            let len = String(val).length;
                            val = String(val).split('.')[0].substr(0, len) + '.' + String(val).split('.')[1];
                            if (Number(val) > this.max) {
                                len = String(this.max).length - 1;
                                val = String(val).split('.')[0].substr(0, len) + '.' + String(val).split('.')[1];
                            }
                        }else{
                            let prevMax = String(this.max).split('.')[0];//小数点前面的值 
                            let lastMax = String(this.max).split('.')[1];                           
                            let len = String(prevMax).length;
                            if(val> prevMax){
                                val = String(prevMax).substr(0, len) + '.'+lastMax;
                            }
                        }
                    }
                    this.showPoper = !hideError;
                    this.content = '输入的数字不能大于最大值为' + this.max
                }
                if(this.cannum){
                    let strVal,str,newVal;
                    if(val % this.cannum === 0){
                        val = val;
                    }else{
                        strVal = val + '';
                        str = strVal.substring(strVal.indexOf('.'), strVal.length);
                        newVal = parseFloat(0 + str);
                        if(newVal < this.cannum){
                            val = Math.floor(val);//向下取整
                        }else if(newVal == this.cannum){
                            val = val;
                        }else{
                            // val = Math.ceil(val);//向上取整
                            val = Math.floor(val);//(大于0.5不向上取整)
                            val += this.cannum;
                        }
                    }
                }
               
            }

            return val;


        },
        formatter(val) {
            if ((val == undefined || val == null || val === '') && this.showReal) {
                return val
            }
            if (this.doublelen && this.doublelen > 0) {
                if (String(val).indexOf('.') > 0) {
                    let vals = String(val).split('.');
                    if (vals[1].length >= this.doublelen) {
                        val = vals[0] + '.' + vals[1].substr(0, this.doublelen)
                    }
                    else {
                        val = (String(val)).padEnd(String(val).length + this.doublelen - vals[1].length, '0')
                    }
                }
                else {
                    // val = (val + '.').padEnd(String(val).length + 1 + this.doublelen, '0') //自动补0
                }
            }
            return val
        },
        blurNumber(e) {
            this.isError = false;
            this.showPoper = false;
            let val = this.inputValue;
            if (this.maxWidth || (val != 0 && !val)) {
                return;
            }
            val = this.validate(val);
            val = this.formatter(val)
            if (val !== this.inputValue) {
                this.inputValue = val
            }
            if (val !== this.value) {
                this.$emit('input', val)
            }
        },
        change(val) {
            this.$emit('change', val);
        },
        handleInput(event) {
            this.isError = false
            let value = event.target.value;
            this.isEmit = true;
            value=value.replace('１',1).replace('２',2).replace('３',3).replace('４',4).replace('５',5)
                .replace('６',6).replace('７',7).replace('８',8).replace('９',9).replace('０',0);
            let val = value;
            val=this.validate(val);
            // val=this.formatter(val)
            if (this.showPoper) {
                this.isError = true

                setTimeout(() => {
                    this.showPoper = false
                }, this.delay)
            }

            this.inputValue = val
            // console.log('val',val,'this.value',this.value)
            if(this.value!=val) {
                this.$emit('input', val)
            }

        },
    }
}
</script>
<style scoped>
.el-input__icon{
    line-height: 32px;
}
.new-number-input.is-error {
    border-color: #FF0000;
}
input:disabled{
    background-color: #dcdddd;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
}
</style>



